from multiprocessing import Process, JoinableQueue, Value
import time
import random

# python的Queue的get和put都为阻塞的, 若想非阻塞则用get(False),put(obj, False)
 
def consumer(q, v, man):
    while True:
        time.sleep(random.randint(1, 3))
        if v.value == 1 and q.empty() is True:
            break
        try:
            food = q.get(False)
        except:
            # get到为空会抛异常
            continue
        print('%s eat %s' % (man, food))
        q.task_done()  # 发送信号给q.join(),说明已经从队列中取走一个数据并处理完毕
    print('Thanks for all~')
 
 
def producer(q, v, man, food):
    for i in range(3):
        time.sleep(random.randint(1, 3))
        food_id = food + str(i)
        q.put(food_id)
        print('%s produce %s' % (man, food_id))
    q.join()    # 等到消费者把自己放入队列中的所有的数据都取走之后，生产者才结束
 
 
if __name__ == '__main__':
    q = JoinableQueue()
    v = Value('b', 0)
    p1 = Process(target=producer, args=(q, v, 'Jim', 'apple'))
    p2 = Process(target=producer, args=(q, v, 'Jenny', 'banana'))
    p3 = Process(target=producer, args=(q, v, 'James', 'peach'))
    c1 = Process(target=consumer, args=(q, v, 'Tom'))
    c2 = Process(target=consumer, args=(q, v, 'Tony'))
    p1.start()
    p2.start()
    p3.start()
    c1.start()
    c2.start()
    p1.join()
    p2.join()
    p3.join()
    v.value = 1
    c1.join()
    c2.join()